import { fileURLToPath, URL } from 'node:url';

import type { UserConfig, ConfigEnv } from 'vite';
import { loadEnv } from 'vite';
import { resolve } from 'path';

import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';

import { OUTPUT_DIR, BASE } from './vite-config/configs/build-config';
import { wrapperEnv } from './vite-config/utils/build-util';

//import { styleImportPlugin } from './vite-config/plugins/style-import-plugin';
import { svgIconsPlugin } from './vite-config/plugins/svg-icons-plugin';
import { gzipCompressionPlugin } from './vite-config/plugins/gzip-compression-plugin';

// https://vitejs.dev/config/

export default ({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();

  const env = loadEnv(mode, root);

  const viteEnv = wrapperEnv(env);

  const { VITE_DROP_CONSOLE, VITE_LEGACY } = viteEnv;

  return {
    base: BASE,
    plugins: [vue(), vueJsx(), svgIconsPlugin(), gzipCompressionPlugin()],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            hack: `true; @import "${resolve('./src/shared/assets/style/less-variable.less')}";`,
          },
          javascriptEnabled: true,
        },
      },
    },
    build: {
      outDir: OUTPUT_DIR,
      polyfillModulePreload: VITE_LEGACY,
      minify: 'terser',
      terserOptions: {
        compress: {
          keep_infinity: true,
          drop_console: VITE_DROP_CONSOLE,
        },
      },
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        // https://rollupjs.org/guide/en/#big-list-of-options
        output: {
          manualChunks: {
            lodash: ['lodash'],
            'ant-design-vue': ['ant-design-vue'],
            echarts: ['echarts'],
            'vue-echarts': ['vue-echarts'],
            nprogress: ['nprogress'],
            overlayscrollbars: ['overlayscrollbars'],
          },
        },
      },
    },
    server: {
      proxy: {
        '/api': {
          target: 'http://127.0.0.1:7000',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
  };
};
